﻿using CNI.Models;
using CNI.Repository.Factory;
using CNI.Repostitory.Interface;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;

namespace CNI.WebApi.IIS.Controllers
{
    public class DeviceController : ApiController
    {
        private static IIngestRepository<DeviceData> ingestRepository = 
            CreateRepositoryFactory().CreateIngestRepository<DeviceData>();
        
        private static IIngestRepositoryFactory CreateRepositoryFactory()
        {
            // Get the factory from config
            string factoryName = CloudConfigurationManager.GetSetting("IngestRepositoryFactory");

            // Get the assembly name from the factory name.
            var className = factoryName.Split('.').Last();
            var assemblyName = factoryName.Substring(0, factoryName.Length - className.Length - 1);

            // Load the assembly and instantiate the ingestion repository.
            Assembly assembly = Assembly.Load(assemblyName);
            object instance = assembly.CreateInstance(factoryName);
            return (IIngestRepositoryFactory)instance;
        }

        [HttpPost]
        public HttpResponseMessage UpdateDeviceStatus([FromBody]DeviceData Data)
        {
            // Ingest the data 
            ingestRepository.Ingest(Data);

            // Return HTTP 201 to client.
            var responseMsg = Request.CreateResponse(HttpStatusCode.Created);
            return responseMsg;
        }
    }
}
